/**
 * Created by dell on 16-12-30.
 */
$(document).ready(function() {
    JudgeBrowser.changeTopBarTextSizeInIE();
    if (JudgeLogin.isLogin()){
        JudgeLogin.bindSignOut(".signOut");
        judgeStaffIsNull();
    }
});

/* 展示列表 */
function showStaffListInfo(data) {
    removeCurrentPersonItem();
    loadDataToTemp(data);
    initPageNumer();
    bindClick();
}



/* 判断员工个数，为空则跳回home.html */
function judgeStaffIsNull() {
    Api.fetchCompaniesStaff(null, null, null, function (result) {
        if (result.data.content.length == 0) {

            gotoOtherInterface("../../html/home/home.html")
        } else {
            console.log(result);
            window.localStorage.staffArrList = JSON.stringify([]);
            callStaffServiceUpdateForm(null, 15, null, "1", "" ,"获取成员列表失败");
            showFilterOption();
            setupManagerName();
        }
    }, function (error) {
        alert("获取员工信息失败");
    })
}

/* 设置管理员名字 */
function setupManagerName() {
    Api.fetchCompanyDetailInfo(function (result) {
        $(".managerBaseInfo").text("管理员：" + result.data.companyName);
    }, function (error) {
        alert("获取管理员名字失败");
    })
}


function bindClick() {

        gotoCompanyInfoInterface();
        gotoAddStaffInterface();
        deleteStaff();
        gotoReviseStaffInterface();
        filterStaff();

}

/* 点击筛选 */
function showFilterOption() {
    $(".search_button").click(function () {

        var selectType = $("span.filterSelected").text();
        selectType = getFilterOption()[selectType];
        filterPersonWithSelectText(selectType, $(".filterInput").val());
        return false;
    });

    $(".filterForm").submit(function () {
        return false;
    })

}

/* 获取筛选信息 */
function filterPersonWithSelectText(type, text) {
    if (text == "") {
        alert("请输入筛选文字");
    } else {
        var contidion = type == "all" ? text : type + ":" + text;
        callStaffServiceUpdateForm(contidion, 15, null, "1", "筛选成功", "筛选失败");
    }


}

/* 删除当前列表的所有信息 */
function removeCurrentPersonItem() {
    var rowItems = $(".userInfoList").children();
    for (var i = 1; i < rowItems.length; i++) {
        $(rowItems[i]).remove();
    }
}

/* 获取接口需要的筛选名字 */
function getFilterOption() {
    return {
        '姓名':'name',
        '联系电话': 'phone',
        '身份证号码':'idNo',
        '部门':'department',
        '全部': 'all'
    }
}


function loadDataToTemp(item) {
    showStaffList(item);
    // bindClickEvent();
}

/* 加载模板 */
function showStaffList(item) {
    for(var info=0;info<item.length;info++) {
        var shopping_string = $(".item_template").html();
        var status = getStaffStatus(item[info].staffBindStatus);
        var sex = getStaffSex(item[info].sex);
        var shopping_item=shopping_string.replace(/userId/,item[info].id)
            .replace(/name/,item[info].name)
            .replace(/sex/,sex)
            .replace(/phone/,item[info].phone)
            .replace(/idNo/,item[info].idNo)
            .replace(/department/,item[info].department)
            .replace(/position/,item[info].position)
            .replace(/doorCardNum/, item[info].doorCardNum)
            .replace(/status/,status);
        $(".userInfoList").append(shopping_item);
    }
    changeFormBackgroundColor();
    changeFormFontSizeInIE();
}

function changeFormFontSizeInIE() {
    if (JudgeBrowser.isIE() || JudgeBrowser.isEdge()) {
        $(".item_list td").addClass('ie_font');
    }
}


/* 根据接口给出的状态返回需要展示的状态数据 */
function getStaffStatus(status) {
    if (status == "BIND_ED") {
        return "已绑定";
    } else {
        return "未绑定"
    }
}

/* 根据接口给出的性别返回需要展示的性别数据 */
function getStaffSex(sex) {
    if (sex == "MALE") {
        return "男";
    } else if (sex == "FEMALE") {
        return "女";
    } else {
        return "未知";
    }
}

/* 根据行数设置表格每一行背景 */
function changeFormBackgroundColor() {
    var rowItems = $(".userInfoList").children();
    for(var i = 0; i < rowItems.length; i++) {
        if (i % 2 != 0) {
            $(rowItems[i]).addClass('staff_back_black');
        }
        if (i == rowItems.length - 1) {
            $(rowItems[i]).addClass('staff_back_white');
        }
        var status = $(rowItems[i]).children()[6];
        if ($(status).text() == "未绑定") {
            $(status).addClass('staff_status_bind');
        }
    }
}

/* 初始化页数 */
function initPageNumer() {
    $(".page span").text("1");
}

/* 点击上一页 */
function clickLastPage() {
    console.log("点击上一页");
    var pageNumber = parseInt($(".page span").text());
    //var staff = JSON.parse(window.localStorage.staffList).data;
    //changePage(pageNumber - 1, staff.prevSkip);
    changePageWithPageNumber(pageNumber);

}

/* 点击下一页 */
function clickNextPage() {
    console.log("点击下一页");
    var pageNumber = parseInt($(".page span").text());
    var staff = JSON.parse(window.localStorage.staffList).data;
    changePage(pageNumber + 1, staff.nextSkip);
}


function changePageWithPageNumber(page) {
    if (page <= 1) {
        alert("已经到第一页了");
    } else {
        var item = JSON.parse(window.localStorage.staffArrList);
        console.log('--------------------');
        console.log(item[page - 2]);
        console.log('--------------------');
        window.localStorage.staffList = JSON.stringify(item[page - 2]);
        showStaffList(item[page - 2].data.content);
        $(".page span").text(page - 1);
    }
}

/* 改变页数 */
function changePage(pageNumber, skip) {
    //post pageNumber
    var staff = JSON.parse(window.localStorage.staffList).data;
    console.log(pageNumber);
    if (pageNumber <= 0) {
        alert("已经到第一页了");
    } else if (staff.hasMore == false && pageNumber > $(".page span").text()) {
        alert("没有更多员工了");
    } else {
        callStaffServiceUpdateForm(null, 15, skip, pageNumber, "", "");
    }
}

/* 调用获取员工列表的接口 */
function callStaffServiceUpdateForm(contidion, limitSize, sortSkip, page, sucPrompt, errPrompt) {
    console.log(contidion + " " + limitSize + " " + sortSkip);
    Api.fetchCompaniesStaff(contidion , limitSize, sortSkip, function (result) {
        if (sucPrompt != "") {
            alert(sucPrompt);
        }
        console.log(result);
        var item = result.data.content;
        window.localStorage.staffList = JSON.stringify(result);
        showStaffListInfo(item);
        $(".page span").text(page);
        saveLocalStaffInfo(result);

    }, function (error) {
        if (errPrompt != "") {
            alert(errPrompt);
        }
        alert(prompt + error);
    });
}

/* 将所有员工信息存入本地 */
function saveLocalStaffInfo(item) {
    var itemArr = JSON.parse(window.localStorage.staffArrList);
    itemArr.push(item);
    window.localStorage.staffArrList = JSON.stringify(itemArr);
}

/* 点击添加 */
function gotoAddStaffInterface(){
    $(".add_button").click(function () {
        // window.location.href='../../html/home/addUserInfo.html';
        gotoOtherInterface('../../html/home/addUserInfo.html');
    })
}

/* 绑定删除按钮和删除界面上的按钮 */
function deleteStaff(){
    showDeleteInterface();
    deleteSelectedStaff();
    cancelDeleteStaff();
}

/* 点击删除界面中的 取消 */
function cancelDeleteStaff() {
    $(".no").click(function () {
        $(".delete_background").hide();
        $(".bomb_box").hide();
        $("body").css({"overflow":"auto"});
    })
}

/* 点击删除界面的 确定 */
function deleteSelectedStaff() {
    $("button.yes").click(function () {
        $(".delete_background").hide();
        $(".bomb_box").hide();
        var deleteUser = $("input[type=checkbox]:checked");
        var selectId = "";
        for(var i=0; i<deleteUser.length;i++){
            selectId += (i == deleteUser.length - 1) ? $(deleteUser[i])[0].id : $(deleteUser[i])[0].id + ",";
        }
        $("body").css({"overflow":"auto"});
        callServiceDeleteStaff(selectId);
    });
}

/* 点击删除按钮弹出删除界面 */
function showDeleteInterface() {
    $(".delete_button").unbind('click').click(function () {
            var deleteUser = $("input[type=checkbox]:checked");
            if (deleteUser.length != 0) {
                $(".delete_background").show();
                $(".bomb_box").show();
                $("body").css({"overflow":"hidden"});
            } else {
                alert("尚未勾选员工");
            }
    });
}



/* 调用删除员工接口 */
function callServiceDeleteStaff(selectId) {
    if (selectId == "") {
        return;
    }
    Api.deleteCompanyStaff(selectId, function (result) {
        if (result.code == 204) {
            window.location.reload();
        } else if (result.code == 403) {
            alert("无权限删除");
        }
    }, function (error) {
        if (error) {
            alert("删除失败");
        }
    })
}

/* 点击企业信息 */
function gotoCompanyInfoInterface() {
    $(".company_info").click(function () {
        // window.location.href='../../html/company/companyInfo.html';
        gotoOtherInterface('../../html/company/companyInfo.html');
    })
}

/* 点击修改 */
function gotoReviseStaffInterface(){
    $(".revise").click(function () {
        var reviseUserInfo = $(this).parent().parent();
        var reviseUserInfoId = $(reviseUserInfo).children()[0];
        var staffId = $(reviseUserInfoId).children()[0].id;
        saveSelectStaffWithId(staffId);
        gotoOtherInterface('../../html/home/reviseUserInfo.html');
        // window.location.href='../../html/home/reviseUserInfo.html';
    })
}

/* 跳入另一个界面 */
function gotoOtherInterface(interface) {
    window.localStorage.removeItem('staffArrList');
    window.localStorage.removeItem('staffList');
    window.location.href = interface;
}


/* 将选择的要修改的员工信息存入本地 */
function saveSelectStaffWithId(id) {
    var staffList = JSON.parse(window.localStorage.staffList).data.content;
    staffList.forEach(function (staff) {
        if (staff.id == id) {
            window.localStorage.selectStaff = JSON.stringify(staff);
        }
    });
}



/* 点击筛选选项 */
function filterStaff() {
    $(".dropdown ul li").unbind('click').click(function () {
        var selectText = $(this).text();
        if (selectText == "全部") {
            window.location.reload();
            $("span.filterSelected").text("");
            $(".filter_all").text('全部');
            $(".filterInput").attr("disabled", "disabled");
        } else {
            $(".filter_all").text(selectText);
            $("span.filterSelected").text(selectText);
            $(".filterInput").attr("disabled",null);
        }
        $(".filter_all").append('<img class="filter_image" src="../../img/home/filter_down.png" />');
    })
}



